package com.fla.millioner;

import java.util.ArrayList;
import java.util.List;

import com.danikula.aibolit.Aibolit;
import com.danikula.aibolit.ServicesResolver;
import com.fla.millioner.ui.support.AndroidUtils;
import com.quietlycoding.android.picker.NumberPicker;
import com.quietlycoding.android.picker.NumberPicker.OnChangedListener;

import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;

public class MillionerApplication extends Application {
    public static final boolean FOR_SAMSUNG = false;
    
    public static final Integer[] LEVELS_DATA = new Integer[] {3000000, 1500000, 800000, 400000, 200000, 100000, 50000, 25000,
        15000, 10000, 5000, 3000, 2000, 1000, 500};

    private static final String BEST_RESULT_KEY = "best_result";
    private static final String SOUND_ENABLED_KEY = "SOUND_ENABLED_KEY";
    private static final String FONT_KEY = "font";

    private static MillionerApplication instance;

    private QuestionService questionService;
    
    private List<OnFontSizeChangedListener> fontSizeChangedListeners;
    
    public interface OnFontSizeChangedListener {
        void onFontSizeChanged(float newFontSize);
    }

    @Override
    public void onCreate() {
        super.onCreate();

        instance = this;
        
        fontSizeChangedListeners = new ArrayList<MillionerApplication.OnFontSizeChangedListener>();

        Aibolit.addServicesResolver(new ServicesResolverImpl());
    }
    
    public void addOnFontSizeChangedListener(OnFontSizeChangedListener listener) {
        fontSizeChangedListeners.add(listener);
    }
    
    public void removeOnFontSizeChangedListener(OnFontSizeChangedListener listener) {
        fontSizeChangedListeners.remove(listener);
    }

    public static MillionerApplication getInstance() {
        if (instance == null) {
            throw new IllegalStateException("Application isn't initialized yet!");
        }
        return instance;
    }

    public QuestionService getQuestionService() {
        if (questionService == null) {
            String storageDir = getExternalCacheDir() == null ? null : getExternalCacheDir().getAbsolutePath();
            questionService = new QuestionService(this, storageDir);
        }
        return questionService;
    }

    public int getBestResult() {
        return getPreferences().getInt(BEST_RESULT_KEY, 0);
    }

    public void setBestResult(int result) {
        getPreferences().edit().putInt(BEST_RESULT_KEY, result).commit();
    }
    
    public boolean isSoundEnabled() {
        return FOR_SAMSUNG ? false : getPreferences().getBoolean(SOUND_ENABLED_KEY, true);
    }
    
    public void setSoundEnabled(boolean soundEnabled) {
        getPreferences().edit().putBoolean(SOUND_ENABLED_KEY, soundEnabled).commit();
    }
    
    public int getCurrentFontSize() {
        return getPreferences().getInt(FONT_KEY, AndroidUtils.isTabletDevice(this) ? 18 : 14);
    }

    public void showChangeFontSizeDialog(Context context) {
        int[] range = AndroidUtils.isTabletDevice(this) ? new int[] {14, 40} : new int[] {10, 23};

        NumberPicker numberPicker = new NumberPicker(context);
        numberPicker.setFormatter(NumberPicker.TWO_DIGIT_FORMATTER);
        numberPicker.setSpeed(100);
        numberPicker.setRange(range[0], range[1]);
        numberPicker.setCurrent(getCurrentFontSize());
        
        final Editor editor = getPreferences().edit();

        numberPicker.setOnChangeListener(new OnChangedListener() {
            @Override
            public void onChanged(NumberPicker picker, int oldVal, int newVal) {
                editor.putInt(FONT_KEY, newVal);
                notifyFontChanged(newVal);
            }
        });

        new AlertDialog.Builder(context)
            .setTitle("Изменить размер шрифта")
            .setView(numberPicker)
            .setPositiveButton("Ok", new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    editor.commit();
                }
            })
            .setNegativeButton("Отмена", new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    notifyFontChanged(getCurrentFontSize());
                }
            })
            .setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    notifyFontChanged(getCurrentFontSize());
                }
            })
            .show();
    }
    
    private void notifyFontChanged(float newFontSize) {
        for (OnFontSizeChangedListener listener : fontSizeChangedListeners) {
            listener.onFontSizeChanged(newFontSize);
        }
    }
    
    private SharedPreferences getPreferences() {
        return PreferenceManager.getDefaultSharedPreferences(this);
    }

    private class ServicesResolverImpl implements ServicesResolver {

        @Override
        public Object resolve(Class<?> serviceClass) {
            if (MillionerApplication.class.isAssignableFrom(serviceClass)) {
                return MillionerApplication.getInstance();
            }
            else if (QuestionService.class.isAssignableFrom(serviceClass)) {
                return getQuestionService();
            }
            throw new IllegalArgumentException("Unknown service: " + serviceClass);
        }
    }
}
